#include "ColorMap.h"
#include <algorithm>
#include <GL/glut.h>

#include <iostream>

using namespace std;

ColorMap::ColorMap()
:
    d_scalar_col(BlackWhite),    
    d_scale(MANUAL),
    d_levels(16),
    d_min(0.0),
    d_max(1.0),
    d_clampMin(0.0),
    d_clampMax(1.0)        
{}

void ColorMap::set(double vy)
{
    float R,G,B;
    
    if (d_scale == AUTO)
        vy = (vy - d_min) / (d_max - d_min);
    else if (d_scale == MANUAL)
        vy = (vy - d_clampMin) / (d_clampMax - d_clampMin);

    if (d_scalar_col == BlackWhite)
            R = G = B = vy;
    else if (d_scalar_col == Rainbow)
            rainbow(vy, &R, &G,&B);
    else if (d_scalar_col == Banded)
    {
        const int NLEVELS = d_levels;
        vy *= NLEVELS; vy = (int)(vy); vy/= NLEVELS;
        rainbow(vy,&R,&G,&B);
    }

    glColor3f(R,G,B);
}

void ColorMap::rainbow(float value, float* R, float* G, float* B)
{
    const float dx=0.8;	
    value = (value < 0) ? 0 : (value > 1) ? 1 : value; // crop value to [0,1];
    value = (6 - 2 * dx) * value + dx;                 // scale value to [dx, 6 - dx]
    *R = max(0.0, (3-fabs(value-4)-fabs(value-5)) / 2.0);
    *G = max(0.0, (4-fabs(value-2)-fabs(value-4)) / 2.0);
    *B = max(0.0, (3-fabs(value-1)-fabs(value-2)) / 2.0);
}

fftw_real ColorMap::usedMax()
{
    fftw_real retVal = d_max;
    if (d_scale == MANUAL)
        retVal = d_clampMax;
    return retVal;
}

fftw_real ColorMap::usedMin()
{
    fftw_real retVal = d_min;
    if (d_scale == MANUAL)
        retVal = d_clampMin;
    return retVal;
}



